/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package cn.story.agent.dao;

import cn.story.agent.domain.Host;
import cn.story.db.DatabaseManager;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 *
 * @author Administrator
 */
public class HostDao {

    public int add(Host host) throws ClassNotFoundException, SQLException {
        Connection con = DatabaseManager.getConnection();
        PreparedStatement statement;
        ResultSet res;
        String sql = "insert into agent_host(title,url,created_at,updated_at) values(?,?,now(),now())";
        statement = con.prepareStatement(sql);
        statement.setString(1, host.getTitle());
        statement.setString(2, host.getUrl());
        int count = statement.executeUpdate();
        res = statement.executeQuery("SELECT LAST_INSERT_ID()");
        if (res.next()) {
            count = res.getInt(1);
        }
        statement.close();

        con.close();

        return count;
    }

    public List<Host> list() throws ClassNotFoundException, SQLException {
        Connection con = DatabaseManager.getConnection();
        PreparedStatement statement;
        ResultSet res;
        List<Host> list = new ArrayList<Host>();

        String sql = "select * from agent_host where id<>? order by id asc";
        statement = con.prepareStatement(sql);
        statement.setInt(1, 0);
        res = statement.executeQuery();

        //rowsAffected=statement.executeUpdate();
        while (res.next()) {
            Host host = new Host();
            host.setId(res.getInt("id"));
            host.setTitle(res.getString("title"));
            list.add(host);
        }
        res.close();
        statement.close();
        con.close();
        return list;
    }
}
